class CourseContentPanel {
    constructor(app) {
        this.app = app;
    }

    // 节选内容管理初始化
    initCourseContentManagement() {
        const contentPanel = document.getElementById('course-content-panel');

        // 添加内容按钮功能
        const addContentBtn = contentPanel.querySelector('#add-content-btn');
        if (addContentBtn) {
            addContentBtn.addEventListener('click', () => this.showContentModal('add'));
        }

        // 搜索功能
        const searchInput = contentPanel.querySelector('.search-input');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => this.handleContentSearch(e));
        }
    }
    
    // 查看音频面板
    selectAudioSubPanel(contentId, contentTitle) {
        // 设置当前选中的内容
        this.app.currentContent = { id: contentId, title: contentTitle };
        
        // 切换到音频面板
        this.app.switchSubPanel('course-audio');
        
        // TODO: 加载该内容下的音频（需要在AudioPanel中实现）
        // this.loadCourseAudios(contentId);
    }

    async loadAllCourses() {
        try {
            // 先获取所有课程阶段
            const stageResponse = await this.app.authenticatedFetch('/api/web/course/getAllStage');
            const stageResult = await stageResponse.json();

            let stageMap = {};
            if (stageResult.code === 200) {
                stageResult.data.forEach(stage => {
                    stageMap[stage.id] = stage.title;
                });
            } else {
                console.error('获取课程阶段失败:', stageResult.msg);
            }

            // 获取所有课程
            let allCourses = [];
            let stagePromises = [];

            Object.keys(stageMap).forEach(stageId => {
                const promise = fetch(`/api/web/course/getAllCourse?csid=${stageId}`)
                    .then(response => response.json())
                    .then(courseResult => {
                        if (courseResult.code === 200) {
                            allCourses = allCourses.concat(courseResult.data || []);
                        } else {
                            console.error(`获取阶段${stageId}的课程失败:`, courseResult.msg);
                        }
                    })
                    .catch(error => {
                        console.error(`加载阶段${stageId}的课程数据失败:`, error);
                    });
                stagePromises.push(promise);
            });

            await Promise.all(stagePromises);

            const tbody = document.querySelector('#courses-table-body');
            tbody.innerHTML = '';

            allCourses.forEach(course => {
                const row = document.createElement('tr');
                const defaultAvatarUrl = Utils.buildFullUrl('/images/default-avatar.png');
                row.innerHTML = `
                    <td>${course.id}</td>
                    <td>${stageMap[course.csid] || '未知阶段'}</td>
                    <td>${course.title}</td>
                    <td>${course.cover ? `<img src="${course.cover}" alt="封面" style="max-width: 100px; max-height: 60px;" data-default="${defaultAvatarUrl}">` : ''}</td>
                    <td>${course.synopsis || ''}</td>
                    <td>${Utils.formatDate(course.create_date) || ''}</td>
                    <td>${Utils.formatDate(course.updata_date) || ''}</td>
                    <td>
                        <button class="btn small view-contents" data-id="${course.id}" data-title="${course.title}">查看内容</button>
                        <button class="btn small edit-course" data-id="${course.id}" data-csid="${course.csid}" data-title="${course.title}" data-synopsis="${course.synopsis || ''}" data-cover="${course.cover || ''}">编辑</button>
                        <button class="btn small danger" data-id="${course.id}">删除</button>
                    </td>
                `;
                tbody.appendChild(row);

                // 为图片绑定错误处理事件
                row.querySelectorAll('img').forEach(img => {
                    img.addEventListener('error', function() {
                        this.src = this.getAttribute('data-default');
                    });
                });

                // 绑定查看内容按钮事件
                row.querySelector('.view-contents').addEventListener('click', (e) => {
                    const courseId = e.target.getAttribute('data-id');
                    const courseTitle = e.target.getAttribute('data-title');
                    this.selectCourseContentSubPanel(courseId, courseTitle);
                });

                // 绑定删除按钮事件
                row.querySelector('.danger').addEventListener('click', (e) => {
                    const courseId = parseInt(e.target.getAttribute('data-id'));
                    const courseTitle = e.target.closest('tr').cells[2].textContent;
                    Utils.confirmAndDelete(courseTitle, () => this.app.coursePanel.deleteCourse(courseId, courseTitle));
                });
            });

            // 绑定所有编辑按钮事件
            tbody.querySelectorAll('.edit-course').forEach(button => {
                button.addEventListener('click', (e) => {
                    const courseData = {
                        id: parseInt(e.target.getAttribute('data-id')),
                        csid: parseInt(e.target.getAttribute('data-csid')),
                        title: e.target.getAttribute('data-title'),
                        synopsis: e.target.getAttribute('data-synopsis'),
                        cover: e.target.getAttribute('data-cover')
                    };
                    this.app.coursePanel.showEditCourseModal(courseData);
                });
            });

            // 如果没有课程，显示提示信息
            if (allCourses.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="8" style="text-align: center;">暂无课程节选</td>`;
                tbody.appendChild(row);
            }

            // 重新绑定搜索功能
            const searchInput = document.querySelector('#course-panel .search-input');
            if (searchInput) {
                searchInput.addEventListener('input', (e) => this.app.coursePanel.handleCourseSearch(e));
            }
        } catch (error) {
            console.error('加载课程数据失败:', error);
            Utils.showError(document.querySelector('#courses-table-body'), '加载课程数据失败');
        }
    }

    async loadCourseContents(courseId) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/course/getAllCourseContent?cid=${courseId}`);
            const result = await response.json();
            
            if (result.code === 200) {
                const contents = result.data || [];
                const tbody = document.querySelector('#contents-table-body');
                tbody.innerHTML = '';

                contents.forEach(content => {
                    const row = document.createElement('tr');
                    const defaultAvatarUrl = Utils.buildFullUrl('/images/default-avatar.png');
                    row.innerHTML = `
                        <td>${content.id}</td>
                        <td>${this.app.currentCourse ? this.app.currentCourse.title : '未知课程'}</td>
                        <td>${content.title}</td>
                        <td>${content.cover ? `<img src="${content.cover}" alt="封面" style="max-width: 100px; max-height: 60px;" data-default="${defaultAvatarUrl}">` : ''}</td>
                        <td>${content.content ? content.content.substring(0, 50) + '...' : ''}</td>
                        <td>${Utils.formatDate(content.create_date) || ''}</td>
                        <td>${Utils.formatDate(content.updata_date) || ''}</td>
                        <td>
                            <button class="btn small view-detail" data-id="${content.id}">查看详情</button>
                            <button class="btn small view-audio" data-id="${content.id}" data-title="${content.title}">查看音频</button>
                            <button class="btn small edit-content" data-id="${content.id}" data-cid="${content.cid}" data-title="${content.title}" data-content="${content.content || ''}" data-cover="${content.cover || ''}">编辑</button>
                            <button class="btn small danger" data-id="${content.id}">删除</button>
                        </td>
                    `;
                    tbody.appendChild(row);

                    // 为图片绑定错误处理事件
                    row.querySelectorAll('img').forEach(img => {
                        img.addEventListener('error', function() {
                            this.src = this.getAttribute('data-default');
                        });
                    });

                    // 绑定查看详情按钮事件
                    row.querySelector('.view-detail').addEventListener('click', (e) => {
                        const contentId = parseInt(e.target.getAttribute('data-id'));
                        const contentItem = contents.find(c => c.id === contentId);
                        if (contentItem) {
                            this.showContentDetail(contentItem);
                        }
                    });

                    // 绑定查看音频按钮事件
                    row.querySelector('.view-audio').addEventListener('click', (e) => {
                        const contentId = parseInt(e.target.getAttribute('data-id'));
                        const contentTitle = e.target.getAttribute('data-title');
                        this.selectAudioSubPanel(contentId, contentTitle);
                    });

                    // 绑定删除按钮事件
                    row.querySelector('.danger').addEventListener('click', (e) => {
                        const contentId = parseInt(e.target.getAttribute('data-id'));
                        const contentTitle = e.target.closest('tr').cells[2].textContent;
                        Utils.confirmAndDelete(contentTitle, () => this.deleteContent(contentId, contentTitle));
                    });
                });

                // 绑定所有编辑按钮事件
                tbody.querySelectorAll('.edit-content').forEach(button => {
                    button.addEventListener('click', (e) => {
                        const contentData = {
                            id: parseInt(e.target.getAttribute('data-id')),
                            cid: parseInt(e.target.getAttribute('data-cid')),
                            title: e.target.getAttribute('data-title'),
                            content: e.target.getAttribute('data-content'),
                            cover: e.target.getAttribute('data-cover')
                        };
                        this.showContentModal('edit', contentData);
                    });
                });

                // 重新绑定搜索功能
                const searchInput = document.querySelector('#course-content-panel .search-input');
                if (searchInput) {
                    searchInput.addEventListener('input', (e) => this.handleContentSearch(e));
                }

                // 如果没有内容，显示提示信息
                if (contents.length === 0) {
                    const row = document.createElement('tr');
                    row.innerHTML = `<td colspan="8" style="text-align: center;">该课程下暂无内容</td>`;
                    tbody.appendChild(row);
                }
            } else {
                console.error('获取课程内容失败:', result.msg);
                Utils.showError(document.querySelector('#contents-table-body'), '获取课程内容失败');
            }
        } catch (error) {
            console.error('加载课程内容数据失败:', error);
            Utils.showError(document.querySelector('#contents-table-body'), '加载课程内容数据失败');
        }
    }

    async initAddContentModal() {
        try {
            // 加载外部模态框模板
            const response = await fetch('/templates/content-modal.html');
            const template = await response.text();
            
            // 创建模态框
            let modal = document.getElementById('content-modal');
            if (!modal) {
                modal = document.createElement('div');
                modal.className = 'modal';
                modal.id = 'content-modal';
                document.body.appendChild(modal);
            }
            
            modal.innerHTML = template;
            
            // 设置标题和按钮文本
            const titleElement = modal.querySelector('h3');
            const submitButton = modal.querySelector('.btn.primary');
            if (titleElement) {
                titleElement.textContent = '添加课程内容';
            }
            if (submitButton) {
                submitButton.textContent = '添加';
            }
            
            return modal;
        } catch (error) {
            console.error('加载添加内容模态框模板失败:', error);
            return null;
        }
    }

    showContentModal(mode, contentData = null) {
        // 检查是否已选择课程（仅在添加模式下检查）
        if (mode === 'add' && !this.app.currentCourse) {
            alert('请先选择一个课程');
            return;
        }
        
        // 根据模式选择合适的初始化方法
        let initMethod;
        if (mode === 'add') {
            initMethod = () => this.initAddContentModal();
        } else {
            initMethod = () => this.initEditContentModal();
        }
        
        // 初始化模态框
        initMethod().then(modal => {
            if (!modal) {
                console.error('无法加载内容模态框模板');
                alert('无法打开内容模态框，请稍后重试');
                return;
            }

            // 获取表单元素
            const form = modal.querySelector('#content-form');
            const idInput = modal.querySelector('#content-id');
            const cidInput = modal.querySelector('#content-cid');
            const courseTitleInput = modal.querySelector('#content-course-title');
            const titleInput = modal.querySelector('#content-title');
            const contentInput = modal.querySelector('#content-text');
            const coverInput = modal.querySelector('#content-cover');
            const previewContainer = modal.querySelector('#content-cover-preview');
            const closeBtn = modal.querySelector('.close');
            const cancelBtn = modal.querySelector('#cancel-content');

            // 根据模式填充表单数据
            if (mode === 'edit' && contentData) {
                // 编辑模式
                if (idInput) {
                    idInput.value = contentData.id;
                }
                
                if (cidInput) {
                    cidInput.value = contentData.cid;
                }
                
                if (courseTitleInput) {
                    courseTitleInput.value = this.app.currentCourse ? this.app.currentCourse.title : '未知课程';
                }
                
                if (titleInput) {
                    titleInput.value = contentData.title;
                }
                
                if (contentInput) {
                    contentInput.value = contentData.content || '';
                }
                
                // 添加封面预览（如果有）
                if (previewContainer) {
                    if (contentData.cover) {
                        const defaultAvatarUrl = Utils.buildFullUrl('/images/default-avatar.png');
                        previewContainer.innerHTML = `<img src="${contentData.cover}" style="max-width: 200px; max-height: 200px; margin-top: 10px;" alt="当前封面" data-default="${defaultAvatarUrl}">`;
                        
                        // 为图片绑定错误处理事件
                        const previewImg = previewContainer.querySelector('img');
                        if (previewImg) {
                            previewImg.addEventListener('error', function() {
                                this.src = this.getAttribute('data-default');
                            });
                        }
                    } else {
                        previewContainer.innerHTML = '';
                    }
                }
            } else {
                // 添加模式
                if (courseTitleInput) {
                    courseTitleInput.value = this.app.currentCourse ? this.app.currentCourse.title : '';
                }
                
                if (cidInput) {
                    cidInput.value = this.app.currentCourse ? this.app.currentCourse.id : '';
                }
                
                // 清空其他字段
                if (titleInput) {
                    titleInput.value = '';
                }
                
                if (contentInput) {
                    contentInput.value = '';
                }
                
                if (previewContainer) {
                    previewContainer.innerHTML = '';
                }
            }

            const closeModal = () => {
                if (modal && modal.parentNode) {
                    modal.remove();
                }
            };

            // 绑定关闭事件
            if (closeBtn) {
                closeBtn.addEventListener('click', closeModal);
            }

            if (cancelBtn) {
                cancelBtn.addEventListener('click', closeModal);
            }

            // 图片预览功能
            if (coverInput) {
                coverInput.addEventListener('change', (e) => Utils.handleImagePreview(e, 'content-cover-preview'));
            }

            // 表单提交事件
            form.addEventListener('submit', (e) => this.handleContentSubmit(e, mode));

            // 显示模态框
            modal.style.display = 'block';
        });
    }

    async initEditContentModal() {
        try {
            // 加载外部模态框模板
            const response = await fetch('/templates/content-modal.html');
            const template = await response.text();
            
            // 创建模态框
            let modal = document.getElementById('content-modal');
            if (!modal) {
                modal = document.createElement('div');
                modal.className = 'modal';
                modal.id = 'content-modal';
                document.body.appendChild(modal);
            }
            
            modal.innerHTML = template;
            
            // 设置标题和按钮文本
            const titleElement = modal.querySelector('h3');
            const submitButton = modal.querySelector('.btn.primary');
            if (titleElement) {
                titleElement.textContent = '编辑课程内容';
            }
            if (submitButton) {
                submitButton.textContent = '更新';
            }
            
            return modal;
        } catch (error) {
            console.error('加载编辑内容模态框模板失败:', error);
            return null;
        }
    }
    async handleContentSubmit(e, mode) {
        e.preventDefault();
        
        const id = document.getElementById('content-id').value;
        const cid = document.getElementById('content-cid').value;
        const title = document.getElementById('content-title').value;
        const content = document.getElementById('content-text').value;
        const coverFile = document.getElementById('content-cover').files[0];

        // 验证必填字段
        if (!title.trim()) {
            alert('请输入内容标题');
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('cid', cid);
        formData.append('title', title.trim());
        formData.append('content', content.trim());
        
        if (coverFile) {
            formData.append('cover', coverFile);
            // 设置封面裁剪尺寸
            formData.append('coverWidth', 1440);
            formData.append('coverHeight', 1032);
        }

        if (mode === 'edit') {
            formData.append('id', id);
        }

        try {
            const url = mode === 'add' ? '/api/web/course/addContent' : '/api/web/course/updateContent';
            const response = await this.app.authenticatedFetch(url, {
                method: 'POST',
                body: formData
            });

            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                alert('课程内容' + (mode === 'add' ? '添加' : '更新') + '成功');
                // 关闭模态框
                const modal = document.getElementById('content-modal');
                if (modal) {
                    modal.remove();
                }
                // 重新加载课程内容列表
                this.loadCourseContents(cid);
            } else {
                alert('操作失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('操作课程内容失败:', error);
            alert('操作课程内容失败: ' + error.message);
        }
    }

    async deleteContent(contentId, contentTitle) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/course/deleteContent/${contentId}`, {
                method: 'DELETE'
            });

            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                alert(`课程内容"${contentTitle}"删除成功`);
                // 重新加载课程内容列表
                if (this.app.currentCourse) {
                    this.loadCourseContents(this.app.currentCourse.id);
                }
            } else {
                alert('删除失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('删除课程内容失败:', error);
            alert('删除课程内容失败: ' + error.message);
        }
    }

    selectCourseContentSubPanel(courseId, courseTitle) {
        // 设置当前选中的课程
        this.app.currentCourse = { id: courseId, title: courseTitle };
        
        // 切换到课程内容面板
        this.app.switchSubPanel('course-content');
        
        // 加载该课程下的内容
        this.loadCourseContents(courseId);
    }

    async initContentDetailModal() {
        try {
            // 加载外部模态框模板
            const response = await fetch('/templates/content-detail-modal.html');
            const template = await response.text();
            
            // 创建模态框
            let modal = document.getElementById('content-detail-modal');
            if (!modal) {
                modal = document.createElement('div');
                modal.className = 'modal';
                modal.id = 'content-detail-modal';
                document.body.appendChild(modal);
            }
            
            modal.innerHTML = template;
            return modal;
        } catch (error) {
            console.error('加载内容详情模态框模板失败:', error);
            return null;
        }
    }

    showContentDetail(content) {
        // 初始化模态框
        this.initContentDetailModal().then(modal => {
            if (!modal) {
                console.error('无法加载内容详情模态框模板');
                alert('无法打开内容详情模态框，请稍后重试');
                return;
            }

            // 填充内容数据
            const titleElement = modal.querySelector('#content-detail-title');
            const coverElement = modal.querySelector('#content-detail-cover');
            const textElement = modal.querySelector('#content-detail-text');
            
            if (titleElement) {
                titleElement.textContent = content.title;
            }
            
            if (coverElement) {
                if (content.cover) {
                    coverElement.src = content.cover;
                    coverElement.style.display = 'block';
                } else {
                    coverElement.style.display = 'none';
                }
            }
            
            if (textElement) {
                textElement.innerHTML = content.content || '';
            }

            // 绑定事件
            const closeBtn = modal.querySelector('.close');
            const closeFooterBtn = modal.querySelector('#close-content-detail');

            const closeModal = () => {
                if (modal && modal.parentNode) {
                    modal.remove();
                }
            };

            if (closeBtn) {
                closeBtn.addEventListener('click', closeModal);
            }

            if (closeFooterBtn) {
                closeFooterBtn.addEventListener('click', closeModal);
            }

            // 显示模态框
            modal.style.display = 'block';
        });
    }

    handleContentSearch(e) {
        const searchTerm = e.target.value.toLowerCase();
        const contentRows = document.querySelectorAll('#contents-table-body tr');

        contentRows.forEach(row => {
            const title = row.cells[2].textContent.toLowerCase();
            const content = row.cells[4].textContent.toLowerCase();

            if (title.includes(searchTerm) || content.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
}